package com.tjs.lucky.domain.activity.service.partake.impl;

import com.db.router.strategy.IDBRouterStrategy;
import com.tjs.lucky.common.ActivityState;
import com.tjs.lucky.common.Ids;
import com.tjs.lucky.common.ResponseCode;
import com.tjs.lucky.common.Result;
import com.tjs.lucky.domain.activity.model.req.PartakeReq;
import com.tjs.lucky.domain.activity.model.vo.ActivityBillVO;
import com.tjs.lucky.domain.activity.model.vo.DisAwardInvoiceVO;
import com.tjs.lucky.domain.activity.model.vo.UserTakeActivityVO;
import com.tjs.lucky.domain.activity.repository.IUserTakeActivityRepository;
import com.tjs.lucky.domain.activity.service.partake.BaseActivityPartake;
import com.tjs.lucky.domain.support.ids.DefindeIdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author: 田佳澍
 * @Description: 活动参与功能实现
 * @DateTime: 2023/5/25 16:17
 **/
@Service
public class ActivityPartakeImpl extends BaseActivityPartake {


    private final Logger logger = LoggerFactory.getLogger(ActivityPartakeImpl.class);

    @Resource
    private IUserTakeActivityRepository userTakeActivityRepository;

    @Resource
    private Map<Ids, DefindeIdGenerator> idGeneratorMap;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private IDBRouterStrategy dbRouter;

    @Override
    public UserTakeActivityVO queryNoConsumedTakeActivityOrder(Long activityId, String uId) {
        return userTakeActivityRepository.queryNoConsumedTakeActivityOrder(activityId, uId);
    }

    @Override
    public Result checkActivityBill(PartakeReq partake, ActivityBillVO bill) {
        // 校验：活动状态
        if (!ActivityState.DOING.getCode().equals(bill.getState())) {
            logger.warn("活动当前状态非可用 state：{}", bill.getState());
            return Result.buildResult(ResponseCode.UN_ERROR, "活动当前状态非可用");
        }

        // 校验：活动日期
        if (bill.getBeginDateTime().after(partake.getPartakeDate()) || bill.getEndDateTime().before(partake.getPartakeDate())) {
            logger.warn("活动时间范围非可用 beginDateTime：{} endDateTime：{}", bill.getBeginDateTime(), bill.getEndDateTime());
            return Result.buildResult(ResponseCode.UN_ERROR, "活动时间范围非可用");
        }

        // 校验：活动剩余参与次数（小于0 或者为null 参与不受限制，大于0有限制，还可以参与）
        if (bill.getStockSurplusCount() != null && bill.getStockSurplusCount() == 0) {
            logger.warn("活动剩余库存非可用 stockSurplusCount：{}", bill.getStockSurplusCount());
            return Result.buildResult(ResponseCode.UN_ERROR, "活动剩余库存非可用");
        }

        // 校验：个人剩余参与次数（小于0 或者为null 参与不受限制，大于0有限制，还可以参与）
        if (bill.getUserTakeLeftCount() != null && bill.getUserTakeLeftCount() == 0) {
            logger.warn("个人领取次数非可用 userTakeLeftCount：{}", bill.getUserTakeLeftCount());
            return Result.buildResult(ResponseCode.UN_ERROR, "个人领取次数非可用");
        }

        return Result.buildSuccessResult();
    }

    /**
     * 活动参与次数-1
     */
    public Result subtractionActivityStock(PartakeReq req) {
        int count = activityRepository.subtractionActivityStock(req.getActivityId());
        if (0 == count) {
            logger.error("扣减活动库存失败 activityId：{}", req.getActivityId());
            return Result.buildResult(ResponseCode.NO_UPDATE);
        }
        return Result.buildSuccessResult();
    }

    /**
     * 参与活动：写入个人参与活动记录
     *
     * @param partake 参与活动请求 ：用户ID、活动ID、参与时间
     * @param bill    活动详情
     * @param takeId  参与活动记录ID
     * @return
     */
    @Override
    public Result savePartRecord(PartakeReq partake, ActivityBillVO bill, Long takeId) {
        // 写入领取活动记录
        userTakeActivityRepository.takeActivity(
                bill.getActivityId(), bill.getActivityName(), bill.getStrategyId(),
                 partake.getUId(),bill.getUserTakeLeftCount(),
                partake.getPartakeDate(), takeId, bill.getStockSurplusCount()
        );
        return Result.buildSuccessResult();
    }

    @Override
    public void updateInvoiceMqState(String uId, Long orderId, Integer mqState) {
        userTakeActivityRepository.updateInvoiceMqState(uId, orderId, mqState);
    }

    @Override
    public void updateGrantState(String uId, Long orderId, Integer grantState) {
        userTakeActivityRepository.updateGrantState(uId, orderId, grantState);
    }

    @Override
    public List<DisAwardInvoiceVO> scanInvoiceMqState(int dbCount, int tbCount) {
        try {
            // 设置路由
            dbRouter.setDBKey(dbCount);
            dbRouter.setTBKey(tbCount);

            // 查询数据
            return userTakeActivityRepository.scanInvoiceMqState();
        } finally {
            dbRouter.clear();
        }
    }
}
